import { asyncRoutes, constantRoutes } from '@/router'
import $httpAxios from '@/utils/httpAxios'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const dTRouter = {}

// 路由列表权限筛选
export function reqFilterAsyncRoutes(reqFilterArr, routers) {
  const res = []
  routers.forEach(route => {
    const tmp = { ...route }
    if (reqFilterArr.includes(tmp.meta && tmp.meta.title) || tmp.hidden) {
      if (tmp.children) {
        tmp.children = reqFilterAsyncRoutes(reqFilterArr, tmp.children)
      }
      res.push(tmp)
    }
  })
  return res
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      let accessedRoutes = []
      // 获取路由权限列表，需要根据我们的路由然后进行处理过滤
      // $httpAxios({ url: 'rxdrepairsaas-usercenter/rest/security/selectFuctionByToken', method: 'get' }).then(res => {
      //   console.log('selectFuctionByToken', asyncRoutes, res)
      //   let reqFilterArr = res.data.map((value, index) => {
      //     return value.name
      //   })
      //   console.log('reqFilterArr', reqFilterArr, asyncRoutes)
      //   accessedRoutes = reqFilterAsyncRoutes(reqFilterArr, asyncRoutes)
      //   console.log('过滤后的权限列表',reqFilterArr,accessedRoutes)
      //   //accessedRoutes = asyncRoutes //d
      //   commit('SET_ROUTES', accessedRoutes)
      //   resolve(accessedRoutes)
      // })

      /*
      * 此处为基础模板使用正常用上面那个
      * */
      accessedRoutes = asyncRoutes
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
